const AppDAO = require('./db/Dao');
const ProjectRepository = require('./db/ProjectRepository');
const FilesRepository = require('./db/FilesRepository');

const dao = new AppDAO('./database.sqlite3');
const projectRepo = new ProjectRepository(dao);
const filesRepo = new FilesRepository(dao);


/**
 * 保存一个包
 * @param {*} req 
 * @param {*} res 
 */
function save (req, res) {
    console.log(req.body);

    // 默认过期时间 
    const EXPIRE = 7;
    const D = 24 * 3600 * 1000;
    const now = Date.now();

    const project = {
        fileList: JSON.stringify(req.body.fileList),
        fileIds: JSON.stringify(req.body.fileIds),
        description: req.body.description,
        filesize: req.body.filesize,
        password: req.body.password || '',
        timestamp: now,
        expireTimestamp: EXPIRE * D + now
    }

    projectRepo.createTable()
        .then(() => projectRepo.create(project))
        .then(rs => {
            console.log('save success ', rs);

            const bf = new Buffer(`Jit_${rs.id}`);
            const data = {
                id: rs.id,
                url: `/p/${bf.toString('base64')}`
            };

            // 更新 文件状态
            const fileTask = [];
            for (let i in req.body.fileIds) {
                fileTask.push(filesRepo.update({
                    id: req.body.fileIds[i],
                    status: 1,
                    projectId: rs.id
                }))
            }
            
            Promise.all(fileTask).then(() => {
                console.log('update file success');
                res.send(data);
            });
        })
        .catch(err => {
            console.log('Error: ', JSON.stringify(err));
            res.status(403).send({
              code: 403,
              err
            });
        })
}


/**
 * 获取一个包
 * @param {*} req 
 * @param {*} res 
 */
function getProject (req, res) {
    console.log(req.body);

    const bf = new Buffer(req.body.id, 'base64')
    const id = bf.toString().replace(/Jit_/, '');

    projectRepo.getById(+id)
        .then(rs => {
            console.log(`getProject id=${id} success`, rs);
            
            rs.fileList = JSON.parse(rs.fileList);
            delete rs.password;
            delete rs.fileIds;

            res.send(rs);
        })
        .catch(err => {
            console.log('Error: ', JSON.stringify(err));
            res.status(403).send({
              code: 403,
              err
            });
        })
}


/**
 * 保存文件
 * @param {*} params
 * @returns
 */
function saveFile(params) {
    return new Promise((resolve, reject) => {
        filesRepo.createTable()
            .then(() => filesRepo.create(params))
            // .then(rs => filesRepo.getById(rs.id))
            .then(rs => {
                console.log('save file success ', rs);
                resolve(rs);
            })
            .catch(err => {
                console.log('Error: ', JSON.stringify(err));
                reject(err);
            });
    });
}

module.exports = {
    save,
    getProject,
    saveFile
};